package com.plum.admin.modules.social.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.plum.admin.common.constant.Constant;
import com.plum.admin.common.util.R;
import com.plum.admin.modules.social.entity.SysSocial;
import com.plum.admin.modules.social.service.ISysSocialService;
import com.plum.admin.modules.social.service.impl.AlipayLoginService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2021/9/16 9:16
 */
@Api(tags = "支付宝登录相关api")
@Controller
@RequestMapping("/social/alipay")
public class AlipayLoginController {

    @Value("${social.alipay.callbackUrl}")
    private String callbackUrl;


    @Value("${social.callbackFeUrl}")
    private String callbackFeUrl;

    @Autowired
    private AlipayLoginService alipayLoginService;
    @Autowired
    private ISysSocialService sysSocialService;
    @GetMapping("/login")
    @ResponseBody
    public R<Object> login(){
        return R.ok(alipayLoginService.getAuthorizeUrl(callbackUrl));
    }
    @RequestMapping(value = "/callback",method = RequestMethod.GET)
    public String callback(
            @RequestParam("app_id") String appId,@RequestParam("source") String source,
            @RequestParam("scope") String scope,@RequestParam("auth_code") String authCode){
        if(StrUtil.isBlank(authCode)){
            return "redirect:" + callbackFeUrl + "?error=" + URLUtil.encode("您未同意授权", "utf-8");
        }
        String accessToken = alipayLoginService.getAccessToken(authCode);
        SysSocial social = alipayLoginService.getUserInfo(accessToken);
        SysSocial sysSocial = sysSocialService.findSocialByOpenId(social.getOpenId(), social.getPlatform());
        if(ObjectUtil.isNull(sysSocial)){
            sysSocialService.save(social);
        }
        return "redirect:"+sysSocialService.getOauthLoginUrl(social,sysSocial,Constant.SOCIAL_TYPE_ALIPAY);
    }
}
